// 硬链接管理（类似 pnpm）

const std = @import("std");

/// 内容寻址存储
pub const ContentStore = struct {
    store_dir: []const u8,
    allocator: std.mem.Allocator,
    
    pub fn init(allocator: std.mem.Allocator) !ContentStore {
        const home = std.os.getenv("HOME") orelse ".";
        const store_dir = try std.fs.path.join(allocator, &[_][]const u8{
            home, ".cz", "store"
        });
        
        // 创建存储目录
        std.fs.cwd().makePath(store_dir) catch {};
        
        return ContentStore{
            .store_dir = store_dir,
            .allocator = allocator,
        };
    }
    
    pub fn deinit(self: *ContentStore) void {
        self.allocator.free(self.store_dir);
    }
    
    /// 添加文件到内容存储
    pub fn addFile(self: *ContentStore, file_path: []const u8) ![]const u8 {
        // 计算文件哈希
        const hash = try self.hashFile(file_path);
        
        // 存储路径：~/.cz/store/<hash>
        const store_path = try std.fs.path.join(
            self.allocator,
            &[_][]const u8{ self.store_dir, hash }
        );
        defer self.allocator.free(store_path);
        
        // 如果文件已存在，直接返回
        std.fs.cwd().access(store_path, .{}) catch {
            // 复制文件到存储
            try std.fs.cwd().copyFile(file_path, std.fs.cwd(), store_path, .{});
        };
        
        return try self.allocator.dupe(u8, hash);
    }
    
    /// 创建硬链接
    pub fn linkFile(
        self: *ContentStore,
        hash: []const u8,
        target_path: []const u8,
    ) !void {
        const store_path = try std.fs.path.join(
            self.allocator,
            &[_][]const u8{ self.store_dir, hash }
        );
        defer self.allocator.free(store_path);
        
        // 创建硬链接
        try std.fs.cwd().link(store_path, target_path, .{});
    }
    
    /// 计算文件哈希
    fn hashFile(self: *ContentStore, file_path: []const u8) ![]const u8 {
        var file = try std.fs.cwd().openFile(file_path, .{});
        defer file.close();
        
        var hasher = std.crypto.hash.sha2.Sha256.init(.{});
        
        var buf: [4096]u8 = undefined;
        while (true) {
            const n = try file.read(&buf);
            if (n == 0) break;
            hasher.update(buf[0..n]);
        }
        
        var hash_bytes: [32]u8 = undefined;
        hasher.final(&hash_bytes);
        
        // 转换为十六进制字符串
        var hash_str = try self.allocator.alloc(u8, 64);
        _ = try std.fmt.bufPrint(hash_str, "{x}", .{std.fmt.fmtSliceHexLower(&hash_bytes)});
        
        return hash_str;
    }
};

/// 安装包（使用硬链接）
pub fn installPackage(
    allocator: std.mem.Allocator,
    package_name: []const u8,
    package_version: []const u8,
) !void {
    std.debug.print("Installing {s}@{s} with hard links...\n", .{
        package_name,
        package_version,
    });
    
    var store = try ContentStore.init(allocator);
    defer store.deinit();
    
    // TODO: 下载包
    // TODO: 添加文件到内容存储
    // TODO: 创建硬链接到 cz-modules/
    
    std.debug.print("✓ Installed {s}@{s}\n", .{package_name, package_version});
}
